package com.rednose.videoplayer.activities;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import com.rednose.videoplayer.model.MediaFiles;
import com.rednose.videoplayer.adapters.PlayListAdapter;
import com.rednose.videoplayer.R;
import com.rednose.videoplayer.controller.LoginController;
import com.rednose.videoplayer.controller.PlayListController;
import com.rednose.videoplayer.model.ListVideo;
import com.rednose.videoplayer.model.User;

import java.util.ArrayList;

public class PlayListActivity extends AppCompatActivity {

    RecyclerView recyclerView;//用于显示视频文件的RecyclerView
    private ArrayList<MediaFiles> videoFilesArrayList = new ArrayList<>();//存储所有的视频文件的model
    private
    static PlayListAdapter playListAdapter;//用于显示视频文件的适配器
    String username;//用户名，用于检索播放列表
    SwipeRefreshLayout swipeRefreshLayout;//用于刷新
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_list);

        //从sharedPreferences获取用户名
        SharedPreferences preferences = getSharedPreferences("user_info", MODE_PRIVATE);
        username = preferences.getString("username","");

        getSupportActionBar().setTitle(username+"的播放列表");//设置标题
        recyclerView = findViewById(R.id.videos_rv_playlist);
        swipeRefreshLayout = findViewById(R.id.swipe_refresh_videos_playlist);//获取刷新控件

        showVideoFiles();

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                showVideoFiles();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    private void showVideoFiles() {
        videoFilesArrayList = fetchMedia(username);//获取所有的视频文件
        playListAdapter = new PlayListAdapter(videoFilesArrayList, this,0);
        recyclerView.setAdapter(playListAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        playListAdapter.notifyDataSetChanged();//通知适配器数据已经改变
    }
    @SuppressLint("Range")
    private ArrayList<MediaFiles> fetchMedia(String username) {
        ArrayList<MediaFiles> videoFiles = new ArrayList<>();
        //获取所有的视频文件
        LoginController loginController = new LoginController(this);
        User user = loginController.getUser(username);
        if(user == null){
            Toast.makeText(this, "用户播放列表为空！", Toast.LENGTH_SHORT).show();
            return videoFiles;
        }
        PlayListController playListController = new PlayListController(this);
        ArrayList<ListVideo> listVideos = playListController.getPlayList(user);
        Context context = getApplicationContext(); // 或者任何其他合适的 Context 实例
        ContentResolver contentResolver = context.getContentResolver();

// 创建一个 URI，指向 MediaStore.Video.Media 的外部内容
        Uri videoUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;

// 遍历 listVideos 数组，获取每个视频的详细信息
        for (ListVideo item : listVideos) {
            String mediaID = item.getMediaID();
            // 创建查询条件，只查询特定的视频记录
            String selection = MediaStore.Video.Media._ID + "=?";
            String[] selectionArgs = { mediaID };

            // 定义要查询的列
            String[] projection = {
                    MediaStore.Video.Media._ID,
                    MediaStore.Video.Media.TITLE,
                    MediaStore.Video.Media.DISPLAY_NAME,
                    MediaStore.Video.Media.SIZE,
                    MediaStore.Video.Media.DURATION,
                    MediaStore.Video.Media.DATA,
                    MediaStore.Video.Media.DATE_ADDED
            };

            // 执行查询
            Cursor cursor = contentResolver.query(
                    videoUri,
                    projection,
                    selection,
                    selectionArgs,
                    null
            );

            // 确保查询成功
            if (cursor != null && cursor.moveToFirst()) {
                // 使用 cursor 获取数据
                String id = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media._ID));
                String title = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.TITLE));
                String displayName = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME));
                String size = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.SIZE));
                String duration = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DURATION));
                String path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));
                String dateAdded = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATE_ADDED));

                // 打印或处理获取的数据
                Log.d("VideoInfo", "ID: " + id + ", Title: " + title + ", Display Name: " + displayName + ", Size: " + size + ", Duration: " + duration + ", Path: " + path + ", Date Added: " + dateAdded);
                MediaFiles mediaFiles = new MediaFiles(id, title, displayName, size, duration, path, dateAdded);
                videoFiles.add(mediaFiles);
                // 确保在完成操作后关闭游标
                cursor.close();
            }
        }
        return videoFiles;
    }
}